package com.koomii.common.file.impl;

import com.koomii.common.file.FileStore;
import com.koomii.common.file.FileType;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: Greey
 * Date: 15-1-9
 * Time: 下午6:58
 * To change this template use File | Settings | File Templates.
 */
public class LocalFileStoreImpl implements FileStore {
    private final static Log log = LogFactory.getLog(LocalFileStoreImpl.class);
    private String storeDir;//文件存储目录   约定以"/" 结尾
    @Override
    public String saveFile(File file, int fileType, String newName) {
        String newFilePath = getNewFilePath(newName,fileType);
        File newFile = new File(storeDir+newFilePath);
        try {
            FileUtils.copyFile(file,newFile);
        } catch (Exception e) {
            log.error("save File error,fileName="+file.getName(),e);
            return null;
        }
        return newFilePath;
    }

    @Override
    public boolean deleteFile(String path, int fileType) {
        try {
            FileUtils.forceDeleteOnExit(new File(storeDir+path));
        } catch (IOException e) {
            log.error("delete file error filePath="+path,e);
            return false;
        }
        return true;
    }
    // 文件目录存储规划:  文件类型/日期/文件
    private static String getNewFilePath(String newName, int fileType) {
        String dir = "";
        switch (fileType){
            case FileType.IMAGE:break;
            case FileType.UPGRADE_PACK:dir="pack";break;
            case FileType.ATTACHED_FILE:dir="attach";break;
        }
        if(StringUtils.isNotEmpty(dir)){
            return dir + "/" + DateFormatUtils.format(new Date(), "yyyyMMdd")+"/"+newName;
        }
        return DateFormatUtils.format(new Date(), "yyyyMMdd")+"/"+newName;
    }

    public void setStoreDir(String storeDir) {
        this.storeDir = storeDir;
    }
}
